package com.leisurexi.gedis.client.controller;

import com.leisurexi.gedis.client.GedisClient;
import com.leisurexi.gedis.client.protocol.RequestProtocol;
import com.leisurexi.gedis.client.protocol.ResponseProtocol;
import com.leisurexi.gedis.client.request.PutReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import java.util.Arrays;
import java.util.Collections;

import static com.leisurexi.gedis.client.constant.GedisCommandConstant.*;


/**
 * Gedis 测试 Controller
 *
 * @author: leisurexi
 * @date: 2021-07-30 14:16
 */
@RestController
@RequestMapping("/gedis")
@Validated
public class GedisController {

    @Autowired
    private GedisClient gedisClient;

    @GetMapping("/{key}")
    public ResponseEntity<String> get(@PathVariable String key) {
        RequestProtocol requestProtocol = new RequestProtocol();
        requestProtocol.setCommand(GET);
        requestProtocol.setArgs(Collections.singletonList(key));
        ResponseProtocol response = gedisClient.send(requestProtocol);
        if (response.isSuccess()) {
            return ResponseEntity.ok(response.getData());
        }
        return ResponseEntity.internalServerError().body(response.getData());
    }

    @PostMapping()
    public ResponseEntity put(@Valid @RequestBody PutReq putReq) {
        RequestProtocol requestProtocol = new RequestProtocol();
        requestProtocol.setCommand(PUT);
        requestProtocol.setArgs(Arrays.asList(putReq.getKey(), putReq.getValue()));
        ResponseProtocol response = gedisClient.send(requestProtocol);
        if (response.isSuccess()) {
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.internalServerError().body(response.getData());
    }

    @DeleteMapping("/{key}")
    public ResponseEntity del(@PathVariable String key) {
        RequestProtocol requestProtocol = new RequestProtocol();
        requestProtocol.setCommand(DEL);
        requestProtocol.setArgs(Collections.singletonList(key));
        ResponseProtocol response = gedisClient.send(requestProtocol);
        if (response.isSuccess()) {
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.internalServerError().body(response.getData());
    }

}
